package gupao.concurrency.threads.aqs;

import gupao.concurrency.threads.Utils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Supplier;

@Slf4j
public class Producer implements Runnable{

    private final ProductsContainer<Product> container;
    private final AtomicBoolean stop;
    private final long timeCost;

    private final Supplier<Product> supplier;

    public Producer(ProductsContainer<Product> container,
                    AtomicBoolean stop,
                    long timeCost,
                    Supplier<Product> supplier) {
        this.container = container;
        this.stop = stop;
        this.timeCost = timeCost;
        this.supplier = supplier;
    }

    @Override
    public void run() {
        while(!stop.get()){
            Product p = supplier.get();
            Utils.sleepIgnoreExp(timeCost);
            try {
                container.put(p);
                if(p == Product.PILL){
                    stop.set(true);
                    log.info("finished all produce task");
                }else{
                    log.info("{} put into container, now container size: {}", p, container.getSize());
                }
            } catch (InterruptedException e) {
                //ignore
            }
        }
    }


}
